var axios = require('axios');
var qs = require('qs')
var cron = require('node-cron');
let URLs = process.argv.filter(item=>item.startsWith("http"));
let check_count = URLs.length;
let NAME = process.env.NAME;
let INTERVAL = process.env.INTERVAL;
let REPORT_URL = process.env.REPORT_URL;

console.log(NAME);
console.log(INTERVAL);
console.log(REPORT_URL);
console.log('tracking started: ',URLs);



function getAllData(URLs){
  return Promise.all(URLs.map(fetchData));
}

function fetchData(URL) {
  return axios
    .get(URL,{
        timeout: 5000
    })
    .then(function(response) {
      console.log('success: ',URL);
      check_count--
      return {
        success: true,
        data: response.data
      };
    })
    .catch(function(error) {
      console.log('fail: ',URL);
      return { success: false };
    });
}

cron.schedule(INTERVAL, () => {

  check_count = URLs.length;

  getAllData(URLs).then(resp=>{
    console.log('==================check list========================');
    // console.log(resp)
    console.log('total error request:',check_count)
    if (check_count===0){
      console.log('report to server everything is fine');
      axios({
        method: 'post',
        url: REPORT_URL,
        data: qs.stringify({
          serverName: process.env.NAME
        }),
        headers: {
          'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
        }
      })
      .then(function(response) {
        console.log('client report: '+process.env.NAME+' finished.');
        console.log('server response: '+response.data);
      })
      .catch(function(error) {
        console.log('report failed');
      });
    }
    console.log('==========================================');

  }).catch(e=>{
    console.log(e)
  })
});

// for (let j = 0; j < process.argv.length; j++) {
//     console.log(j + ' -> ' + (process.argv[j]));
// }
